//
//  MyVC.m
//  爱寻找
//
//  Created by qianfeng0 on 16/6/23.
//  Copyright © 2016年 王超. All rights reserved.
//

#import "MyVC.h"
#import "Helper.h"
#import "AppDelegate.h"
#import "CollectionVC.h"
#import "LXAlertView.h"

@interface MyVC ()<UITableViewDataSource,UITableViewDelegate>
{
    //头部视图
    UIImageView * _headerImageView;
    //tableView
    UITableView * _tableView;
    
    //半透明View
    UIView * _darkView;
}
@property (nonatomic,strong) NSArray * logoArray;
@property (nonatomic,strong) NSArray * titleArray;

@property (nonatomic,assign) BOOL isDark;
@end

@implementation MyVC

//定义静态的全局变量，方便统一修改
static float originalImageHeight = 150;

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    
    
    [self initData];
    [self createUI];
}
#pragma mark - 初始化数据
- (void)initData {
    
    //标示判断是不是黑夜
    _isDark = YES;
    
    self.logoArray = @[@"iconfont-shoucang",@"iconfont-qinglihuancun",@"iconfont-yejianfuwu",@"iconfont-zhengguiicon40",@"iconfont-wenti",@"iconfont-guanyuwomen",@"iconfont-shezhi"];
    self.titleArray = @[@"我的收藏",@"清除缓存",@"夜间模式",@"推送消息",@"问题反馈",@"关于我们",@"设置"];
    
    self.navigationController.tabBarItem.selectedImage = [[UIImage imageNamed:@"iconfont-iconfontsvgman-2"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
}
#pragma mark - 创建UI
- (void)createUI {
    
    //创建tableView
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, ScreenWidth, ScreenHeight - 64) style:UITableViewStylePlain];
    
    //设置代理
    _tableView.delegate = self;
    _tableView.dataSource = self;
    
    [self.view addSubview:_tableView];
    
    //去掉多余的线条
    _tableView.tableFooterView = [[UIView alloc] init];
    
    //头部视图，并不是将视图设置为tableView的tableHeaderView,而是将视图作为子视图添加到tableView上
    _headerImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, -originalImageHeight, ScreenWidth, originalImageHeight - 64)];
    _headerImageView.image = [UIImage imageNamed:@"55a36bb085d4c182.jpg!600x600.jpg"];
    [_tableView addSubview:_headerImageView];
    
    //需要设置tableView的内容从originalImageHeight开始显示,UIEdgeInsetsMake参数的顺序的上左下右
    _tableView.contentInset = UIEdgeInsetsMake(originalImageHeight, 0, 0, 0);
    
    //夜间模式
    _darkView = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    
}
#pragma mark - 代理实现方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.logoArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    //1.cell的标识(用来区分cell的类型)
    static NSString * identifier = @"myCell";
    
    //2.按照标识在复用池中查找
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    
    //3.如果复用池找找不到需要的cell，就创建新的cell
    if (nil == cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        
        if (indexPath.row == 0 || indexPath.row == 1 || indexPath.row == 4 || indexPath.row == 5 || indexPath.row == 6) {
            //添加尾部指示箭头
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            
            cell.imageView.image = [UIImage imageNamed:self.logoArray[indexPath.row]];
            cell.textLabel.text = self.titleArray[indexPath.row];
        }
        
        if (indexPath.row == 2 || indexPath.row == 3) {
            //添加开关
            UISwitch * swi = [[UISwitch alloc]initWithFrame:CGRectMake(ScreenWidth - 70, 5, 40, 34)];
            
            //设置内嵌颜色,默认是绿色的
            //swi.onTintColor = [UIColor blueColor];
            //设置边框颜色
            //swi.tintColor = [UIColor redColor];
            swi.tag = indexPath.row;
            //添加响应方法
            [swi addTarget:self action:@selector(swiChangeValue:) forControlEvents:UIControlEventValueChanged];
            
            
            [cell.contentView addSubview:swi];
            
            if (indexPath.row == 2) {
                if (_isDark) {
                    cell.imageView.image = [UIImage imageNamed:self.logoArray[indexPath.row]];
                    cell.textLabel.text = self.titleArray[indexPath.row];
                }
            }else {
                cell.imageView.image = [UIImage imageNamed:self.logoArray[indexPath.row]];
                cell.textLabel.text = self.titleArray[indexPath.row];
            }
        }
    }
    
    
    //4.返回cell
    return cell;
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.row == 0) {
        
        //页面跳转
        UIStoryboard * stb = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
        CollectionVC * vc = [stb instantiateViewControllerWithIdentifier:@"CollectionVC"];
        
        //隐藏tabbar
        vc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:vc animated:YES];
        
    } if (indexPath.row == 1) {
        //清理缓存
        [self caculateFolderSizeAtPath:[self getPath]];
    }
}
#pragma mark - 实现scrollView的代理方法
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    //头图放大的实现思路：通过scrolLView的滑动效果获取到它的偏移量，从而改变图片的frame
    if (scrollView == _tableView) {
        //获取scrollView的偏移量
        //纵向偏移量
        float yOffset = scrollView.contentOffset.y;
        //横向偏移量,随着纵向偏移量的变化而变化
        float xOffset = (yOffset + originalImageHeight) / 2;
        //改变图片的大小
        if (yOffset < -originalImageHeight) {
            CGRect rect = _headerImageView.frame;
            //纵坐标
            rect.origin.y = yOffset;
            //高度
            rect.size.height = -yOffset;
            //横坐标
            rect.origin.x = xOffset;
            //宽度
            rect.size.width = ScreenWidth + fabs(xOffset) * 2;
            _headerImageView.frame = rect;
            
        }
        
    }
    
}
#pragma mark - 按钮响应
-(void)swiChangeValue:(UISwitch *)swi
{
    UITableViewCell * cell = [_tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:2 inSection:0]];
    
    if (swi.tag == 2) {
        //夜间模式:实质上在window上覆盖一层半透明的view
        if (swi.on) {
            //添加半透明view
            //首先获取window
            //设置半透明颜色
            
            _darkView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.3];
            UIApplication * app = [UIApplication sharedApplication];
            AppDelegate * delegate = app.delegate;
            
            [delegate.window addSubview:_darkView];
            
            
            
            cell.imageView.image = [UIImage imageNamed:@"iconfont-rijian"];
            cell.textLabel.text = @"日常模式";
            
            _isDark = NO;
            
            [_tableView reloadData];
            
            //关闭view的用户交互
            _darkView.userInteractionEnabled = NO;
            
        } else {
            //移除半透明view
            [_darkView removeFromSuperview];
            _isDark = YES;
            
            cell.imageView.image = [UIImage imageNamed:@"iconfont-yejianfuwu"];
            cell.textLabel.text = @"夜间模式";
            [_tableView reloadData];
        }
    }
}

#pragma mark - 清理缓存
#pragma mark - 计算缓存文件的大小
//首先找到缓存文件的路径
- (NSString *)getPath {
    
    //在沙盒目录下，分为Documents，Library,Temp=三个文件夹，缓存文件夹位于library文件夹下的cache
    NSString * path = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject;
    
    return path;
}
//计算缓存文件夹的大小
- (CGFloat)caculateFolderSizeAtPath:(NSString *)path {
    
    //获取文件管理类
    NSFileManager * fileManager = [NSFileManager defaultManager];
    
    CGFloat folderSize = 0.0;
    
    //判断指定路径下文件管理是否有文件
    if ([fileManager fileExistsAtPath:path]) {
        
        //找到缓存文件夹下的子文件
        NSArray * fileArray = [fileManager subpathsAtPath:path];
        for (NSString * fileName in fileArray) {
            //获取每个子文件的路径
            NSString * filePath = [path stringByAppendingPathComponent:fileName];
            //计算每个子文件的大小
            CGFloat fileSize = [fileManager attributesOfItemAtPath:filePath error:nil].fileSize;
            //计算值是以字节为单位的
            folderSize += fileSize / 1024.0 / 1024.0;
            
        }
        
        //清楚
        [self deleteFolderSizeWith:folderSize];
        
        return folderSize;
    } else {
        return 0.0;
    }
    
}
//给用户弹出提示，让用户自由选择是否清楚
- (void)deleteFolderSizeWith:(CGFloat)folderSize {
    
    if (folderSize > 0.01) {
        
        LXAlertView * alertView = [[LXAlertView alloc] initWithTitle:@"温馨提示" message:[NSString stringWithFormat:@"当前有%.2fM缓存，是否清楚",folderSize] cancelBtnTitle:@"取消" otherBtnTitle:@"确定" clickIndexBlock:^(NSInteger clickIndex) {
            
            if (clickIndex == 1) {
                //彻底清除缓存
                [self clearCacheAtPath:[self getPath]];
                LXAlertView * alert = [[LXAlertView alloc] initWithTitle:@"温馨提示" message:@"清除成功" cancelBtnTitle:nil otherBtnTitle:@"确定" clickIndexBlock:nil];
                alert.animationStyle = LXASAnimationTopShake;
                [alert showLXAlertView];
            }
            
        }];
        alertView.dontDissmiss = NO;
        alertView.animationStyle = LXASAnimationTopShake;
        [alertView showLXAlertView];
        
    } else {
        
        //提示没有更多的缓存需要清理
        LXAlertView * alerView = [[LXAlertView alloc] initWithTitle:@"" message:@"当前没有缓存可清理" cancelBtnTitle:nil otherBtnTitle:@"确定" clickIndexBlock:^(NSInteger clickIndex) {
            
        }];
        alerView.animationStyle = LXASAnimationLeftShake;
        [alerView showLXAlertView];
    }
}

- (void)clearCacheAtPath:(NSString *)path {
    
    NSFileManager * fileManager = [NSFileManager defaultManager];
    
    if ([fileManager fileExistsAtPath:path]) {
        
        //获取子文件
        NSArray * fileArray = [fileManager subpathsAtPath:path];
        for (NSString * fileName in fileArray) {
            //过滤掉不清除的文件
            if ([fileName hasSuffix:@".mp3"]) {
                NSLog(@"不清除");
                return;
            } else {
                //全部清楚
                //获取子文件的路径
                NSString * filePath = [path stringByAppendingPathComponent:fileName];
                [fileManager removeItemAtPath:filePath error:nil];
            }
        }
    }
}
@end
